package com.traffic.between.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.MD5Util;
import com.traffic.between.util.Xml2JsonUtil;

@SuppressWarnings("deprecation")
public class HangzleyaoServiceImpl {
	private static Logger logger = Logger.getLogger(HangzleyaoServiceImpl.class);
	public static HangzleyaoServiceImpl service = new HangzleyaoServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.HZLY_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.HZLY_ORDERSTATUS_URL;
	private static String HZLY_APPKEY = BetweenProperties.HZLY_APPKEY;
	private static String HZLY_SECURITYKEY = BetweenProperties.HZLY_SECURITYKEY;


	@SuppressWarnings({ "resource" })
	public  String order(String productId, String phoneNo, String cstmOrderNo, String buyNum, String unitPrice) {
		logger.info("between- 杭州乐尧订购请求参数: params productId = " + productId + ", phoneNo = " + phoneNo
				+ ", cstmOrderNo = " + cstmOrderNo);

		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		Map<String, String> pars = new HashMap<String, String>();
		pars.put("userNo", HZLY_APPKEY); // 合作方用户编号
		pars.put("goodsId", productId);// 商品编号
		pars.put("ptOrderNo", cstmOrderNo);// 合作方订单编号
		pars.put("ptPayTime", time);// 合作方买家付款时间
		pars.put("buyNum", buyNum);// 购买数量
		pars.put("unitPrice", unitPrice);// 该商品供货单价
		pars.put("totalPrice", unitPrice);// 总价
		pars.put("gameAccount", phoneNo);// 充值号码
		pars.put("notifyUrl", "http://localshot");// 异步通知地址
		pars.put("merchantIP", "127.0.0.1");// 最终购买用户IP地址,没有则127.0.0.1

		String sig = MD5Util.MD5(HZLY_APPKEY + productId + cstmOrderNo + time + buyNum + "" + unitPrice + unitPrice
				+ phoneNo + "127.0.0.1" + HZLY_SECURITYKEY);
		pars.put("sign", sig.toLowerCase());

		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(1000));

		httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(3000));

		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/20100101 Firefox/17.0");

		httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
		String response = null;
		try {
			List<BasicNameValuePair> nvps = null;
			if ((pars != null) && (!(pars.isEmpty()))) {
				nvps = new ArrayList<BasicNameValuePair>();
				Iterator it = pars.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
				}

				UrlEncodedFormEntity encodeform = new UrlEncodedFormEntity(nvps, Charset.forName("utf-8"));
				httpPost.setEntity(encodeform);
			}
			HttpResponse httpresponse = httpclient.execute(httpPost);
			if (httpresponse.getStatusLine().getStatusCode() == 200) {
				InputStream stream = httpresponse.getEntity().getContent();
				// HttpEntity httpEntity = httpresponse.getEntity();
				// Header header = httpEntity.getContentEncoding();
				// String encode = null;
				// if (header != null) {
				// encode = header.getName();
				// }
				StringBuilder sb = new StringBuilder();
				InputStreamReader inReader = new InputStreamReader(stream, "utf-8");

				BufferedReader reader = new BufferedReader(inReader);
				String rdline = null;
				while ((rdline = reader.readLine()) != null) {
					sb.append(rdline).append("\n");
				}
				reader.close();
				response = sb.toString().trim();
				response = Xml2JsonUtil.xml2JSON(response.toString().trim());
				logger.info("between- 杭州乐尧流量状态响应json:  " + response.toString());
				net.sf.json.JSONObject resultJson = net.sf.json.JSONObject.fromObject(response);
				net.sf.json.JSONObject resultResponse = (net.sf.json.JSONObject) resultJson.get("response");

				String resMsg = String.valueOf(resultResponse.get("resMsg"));
				if ("SUCCESS".equals(resMsg)) {
					response = "{\"resultCode\": \"00\",\"errorDesc\":" + "\"订购中" + "\"" + "}";
				} else {// 订购失败
					response = "{\"resultCode\": \"01\",\"errorDesc\":" + "\"订购失败" + "\"" + "}";
				}
				httpPost.releaseConnection();
			}
		} catch (Exception e) {
		
			logger.error("between- 杭州乐尧流量订购请求时的响应异常: " + e);

		} finally {
			httpPost.releaseConnection();
		}
		return response;

	}

	@SuppressWarnings({ "resource" })
	public  String orderStatus(String cstmOrderNo) {
		logger.info("between- 杭州乐尧状态请求参数: params  cstmOrderNo = " + cstmOrderNo);

		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		Map<String, String> pars = new HashMap<String, String>();
		pars.put("userNo", HZLY_APPKEY); //
		pars.put("ptOrderNo", cstmOrderNo);// 合作方用户编号

		String sig = MD5Util.MD5(HZLY_APPKEY + cstmOrderNo + HZLY_SECURITYKEY);
		pars.put("sign", sig.toLowerCase());

		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(1000));

		httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(3000));

		HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:17.0) Gecko/20100101 Firefox/17.0");

		httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
		String response = null;
		try {
			List<BasicNameValuePair> nvps = null;
			if ((pars != null) && (!(pars.isEmpty()))) {
				nvps = new ArrayList<BasicNameValuePair>();
				Iterator it = pars.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
				}

				UrlEncodedFormEntity encodeform = new UrlEncodedFormEntity(nvps, Charset.forName("utf-8"));
				httpPost.setEntity(encodeform);
			}
			HttpResponse httpresponse = httpclient.execute(httpPost);
			if (httpresponse.getStatusLine().getStatusCode() == 200) {
				InputStream stream = httpresponse.getEntity().getContent();
				StringBuilder sb = new StringBuilder();
				InputStreamReader inReader = new InputStreamReader(stream, "utf-8");

				BufferedReader reader = new BufferedReader(inReader);
				String rdline = null;
				while ((rdline = reader.readLine()) != null) {
					sb.append(rdline).append("\n");
				}
				reader.close();
				response = Xml2JsonUtil.xml2JSON(sb.toString().trim());
				logger.info("between- 杭州乐尧流量状态响应json:  " + response.toString());
				net.sf.json.JSONObject resultJson = net.sf.json.JSONObject.fromObject(response);
				net.sf.json.JSONObject resultResponse = (net.sf.json.JSONObject) resultJson.get("response");

				String resMsg = String.valueOf(resultResponse.get("resMsg"));
				String failedReason = String.valueOf(resultResponse.get("failedReason"));
				String status = String.valueOf(resultResponse.get("status"));

				if ("SUCCESS".equals(resMsg)) {
					if ("ORDER_SUCCESS".equals(status)) {
						response = "{\"resultCode\": \"00\",\"errorDesc\":\"" + failedReason + "\"}";

					} else if ("ORDER_FAILED".equals(status)) {

						response = "{\"resultCode\": \"02\",\"errorDesc\":\"" + failedReason + "\"}";
					} else {
						response = "{\"resultCode\": \"01\",\"errorDesc\":\"" + failedReason + "\"}";
					}
				} else {// 订购中
					response = "{\"resultCode\": \"01\",\"errorDesc\":\"" + failedReason + "\"}";
				}

				httpPost.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("between- 杭州乐尧流量状态请求时的响应异常: " + e);
			return "{\"resultCode\": \"01\",\"errorDesc\":" + "\"订购中" + "\"" + "}";
		} finally {
			httpPost.releaseConnection();
		}
		return response;

	}
}
